package com.dxt.common;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class JsonUtil {

    public static String xmlToJson(String xml){
        XMLSerializer xmlSerializer = new XMLSerializer();
        String result = xmlSerializer.read(xml).toString();
        return result;
    }

    public static String jsonToXml(String jsonStr){
        XMLSerializer xmlSerializer = new XMLSerializer();
        String result = xmlSerializer.write(JSONSerializer.toJSON(jsonStr));
        return result;
    }

    public static String jsonToUrlParams(String jsonStr){
        Map mapType = JSON.parseObject(jsonStr,Map.class);
        StringBuffer stringBuffer = new StringBuffer();
        for (Object obj : mapType.keySet()){
            stringBuffer.append("&");
            stringBuffer.append(obj+"="+mapType.get(obj));
        }
        return stringBuffer.toString();
    }

    public static String getSendJson(String reqJson){
        Map<String,Object> map = new HashMap<>();
        map.put("body",reqJson);
        JSONObject sendJson = new JSONObject(map);
        return sendJson.toJSONString();
    }

    public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", null);
        String a = jsonObject.getString("username");
        System.out.println("a="+ StringUtils.stripToEmpty(a));
        System.out.println(jsonObject.toString());

        String xml = jsonToXml(jsonObject.toString());
        System.out.println("xml:" + xml);
        String str = xmlToJson(xml);
        System.out.println("to_json" + str);
        String params = jsonToUrlParams(jsonObject.toJSONString());
        System.out.println(params);

    }
}
